const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const secretKey = 'thisisasecretkey'; // 密钥，根据实际情况进行设置
const client = require('../datebase/db')

router.post('/api/login', (req, res) => {
    const { email, password } = req.body;
    client.query('SELECT * FROM users WHERE email=$1', [email], (err, result) => {
      if (err) {
        console.error('Failed to query database:', err);
        res.status(500).json({ success: false, message: '邮箱或密码错误' });
      } else {
        if (result.rows.length > 0) {
          const hash = result.rows[0].password; // 获取存储的hash值
          bcrypt.compare(password, hash, function (err, result) {
            if (result) {
              // 生成Token
              const payload = { email: email, exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24 * 7)}; // Token中包含的信息，这里只包含了用户email
              const token = jwt.sign(payload, secretKey); 
              // 在登录成功后，将Token存储在数据库中
              client.query('UPDATE users SET token=$1, exp=$2 WHERE email=$3', [token, payload.exp, email], (err, result) => {
                if (err) {
                  console.error('Failed to update database:', err);
                  res.status(500).json({ success: false, message: '服务器内部错误' });
                } else {
                  res.json({ success: true, message: '登录成功', token: token });
                }
              });
            } else {
              // 密码不匹配，登录失败
              res.status(401).json({ success: false, message: '邮箱或密码错误' });
            }
          });
        } else {
          // 邮箱不存在
          res.status(401).json({ success: false, message: '邮箱不存在' });
        }
      }
    });
  });
  
  router.post('/api/register', (req, res) => {
    const { email, username, password } = req.body;
    // 首先查询数据库中是否已经存在该邮箱
    const checkEmailQuery = "SELECT * FROM users WHERE email = $1";
    client.query(checkEmailQuery, [email], (err, result) => {
      if (err) {
        console.error('Failed to query database:', err);
        res.status(500).send('Server Error');
      } else {
        if (result.rows.length > 0) {
          // 邮箱已经存在
          res.status(400).send('邮箱已经存在');
        } else {
          // 邮箱不存在，将数据写入数据库中
          const saltRounds = 10; // 设置盐的数量
          bcrypt.genSalt(saltRounds, function (err, salt) {
            bcrypt.hash(password, salt, function (err, hash) {
              const insertUserQuery = "INSERT INTO users (email, username, password) VALUES ($1, $2, $3)";
              client.query(insertUserQuery, [email, username, hash], (err, result) => {
                if (err) {
                  console.error('Failed to insert data into database:', err);
                  res.status(500).send({ success: false, message: 'Server Error' });
                } else {
                  res.status(200).send({ success: true, message: '注册成功' });
                }
              });
            });
          });
        }
      }
    });
  });
  
  //请求mapview1
  router.get('/api/mapview1', (req, res) => {
    //获取请求头中的token
    const token = req.headers.authorization.split(' ')[1];
    //查询数据库中是否已经存在该token
    client.query('SELECT * FROM users WHERE token=$1', [token], (err, result) => {
      if (err) {
        console.error('Failed to query database:', err);
        res.status(500).json({ success: false, message: '服务器内部错误' });
      } else {
        if (result.rows.length > 0) {
          // Token存在，返回状态码200
          res.status(200).json({ success: true, message: '请求成功', data: {} });
        } else {
          // Token不存在或已过期，返回状态码401
          res.status(401).json({ success: false, message: 'Token无效或已过期' });
        }
      }
    });
  });
  //请求mapview2访问权限
  router.get('/api/mapview2', (req, res) => {
    //获取请求头中的token
    const token = req.headers.authorization.split(' ')[1];
    //查询数据库中是否已经存在该token
    client.query('SELECT * FROM users WHERE token=$1', [token], (err, result) => {
      if (err) {
        console.error('Failed to query database:', err);
        res.status(500).json({ success: false, message: '服务器内部错误' });
      } else {
        if (result.rows.length > 0) {
          // Token存在，返回状态码200
          res.status(200).json({ success: true, message: '请求成功', data: {} });
        } else {
          // Token不存在或已过期，返回状态码401
          res.status(401).json({ success: false, message: 'Token无效或已过期' });
        }
      }
    });
  });
  //请求mapview3访问权限
  router.get('/api/mapview3', (req, res) => {
    //获取请求头中的token
    const token = req.headers.authorization.split(' ')[1];
    //查询数据库中是否已经存在该token
    client.query('SELECT * FROM users WHERE token=$1', [token], (err, result) => {
      if (err) {
        console.error('Failed to query database:', err);
        res.status(500).json({ success: false, message: '服务器内部错误' });
      } else {
        if (result.rows.length > 0) {
          // Token存在，返回状态码200
          res.status(200).json({ success: true, message: '请求成功', data: {} });
        } else {
          // Token不存在或已过期，返回状态码401
          res.status(401).json({ success: false, message: 'Token无效或已过期' });
        }
      }
    });
  });
  
  
  //请求用户名和email
  router.get('/api/user', (req, res) => {
    const token = req.headers.authorization.split(' ')[1];
    client.query('SELECT * FROM users WHERE token=$1', [token], (err, result) => {
      if (err) {
      console.error('Failed to query database:', err);
      res.status(500).json({ success: false, message: '服务器内部错误' });
    }else {
      if (result.rows.length > 0) {
        const user = result.rows[0];
        // Token存在，返回username和email
        res.json({ success: true, message: '请求成功',username: user.username, email: user.email});
      } else {
        // Token不存在或已过期，返回状态码401
        res.json({ success: false, message: 'Token无效或已过期' });
      }
    }
    });
  });

module.exports = router